<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="t('routes.demo.partManager.associatedFigureDoc')"
      @register="registerModal"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :destroyOnClose="true"
      :minHeight="450"
      :width="1200"
    >
      <Row :gutter="24">
        <Col :xs="24" :sm="24" :md="24" :lg="4" :xl="4">
          <div style="overflow-y: scroll; overflow-x: hidden; height: 400px">
            <Tree :tree-data="dataSource" @select="selectDir" />
          </div>
        </Col>
        <Col
          :xs="1"
          :sm="1"
          :md="1"
          :lg="1"
          :xl="1"
          style="display: flex; justify-content: center"
        />
        <Col :xs="24" :sm="24" :md="24" :lg="19" :xl="19">
          <BasicTable @register="registerTable" :searchInfo="searchInfo">
            <!-- 创建时间 -->
            <template #creattime="{ text: creattime }">
              <span>
                {{ proxy.$filters.filterTime(creattime) }}
              </span>
            </template>
            <!-- 创建时间 -->
            <template #state="{ text: state }">
              <span>
                {{ proxy.$filters.filterDocumentStatus(state) }}
              </span>
            </template>
            <!-- 是否为关联文件 -->
            <template #isshortcut="{ text: isshortcut }">
              <span>
                {{ proxy.$filters.filterIsRelated(isshortcut) }}
              </span>
            </template>
            <!-- 是否所属零件 -->
            <template #isPartAttachment="{ text: isPartAttachment }">
              <span>
                {{ isPartAttachment === '1' ? t('common.yes') : t('common.no') }}
              </span>
            </template>
            <!-- 零件信息 -->
            <template #partInfo="{ text: partInfo }">
              <span>
                <Tooltip :title="partInfoTitle(partInfo)">
                  {{
                    partInfo != null
                      ? `零件代号：${partInfo.partThitObjectId}-零件名称：${
                          partInfo.partName
                        }-零件类型：${
                          partInfo.partType
                        }-零件状态：${proxy.$filters.filterPartStatus(
                          partInfo.partStatus,
                        )}-零件版本：${partInfo.partVersion}`
                      : '无'
                  }}
                </Tooltip>
              </span>
            </template>
          </BasicTable>
        </Col>
      </Row>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  /**
   * 模块名:图文档选择公共弹窗组件
   * 代码描述: 弹窗共分为左右2模块，左侧为目录，右侧为点击目录显示列表，列表首列为单选框，选中后点击弹窗确认按钮，即选择成功
   * 作者:张泽源
   * 创建时间:2024/02/27 14:19:13
   */
  import { ref, getCurrentInstance } from 'vue';
  import { Row, Col, Tree, Tooltip } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable } from '/@/components/Table';
  import { getDocumentColumns, getDocumentConfig } from '../tableData';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { getDirectoryLevel, getPrdFileList } from '/@/api/demo/document';
  const emit = defineEmits(['register', 'success', 'successDoc']);
  const { t } = useI18n();
  const { proxy }: any = getCurrentInstance();
  const dataSource = ref<any[]>([]);
  const getDirParam = ref<number>(0);
  const currentRecord = ref<any>({});
  const searchInfo = ref<any>({
    CurrentDirId: '',
  });
  const selectType = ref<string>(''); // 选择类型
  const fromRecord = ref<any>({});

  // 计算零件信息
  const partInfoTitle = (partInfo) => {
    if (!partInfo) {
      return '暂无零件信息';
    }
    const { partThitObjectId, partName, partType, partStatus, partVersion } = partInfo;
    // 假设你在全局过滤器里定义了 filterDocumentStatus
    const filterState = proxy.$filters.filterPartStatus(partStatus);
    // 多行显示，每行一个字段
    return [
      `零件代号：${partThitObjectId}`,
      `零件名称：${partName}`,
      `零件类型：${partType}`,
      `零件状态：${filterState}`,
      `零件版本：${partVersion}`,
    ].join('\n');
  };

  // 提交
  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true });
      if (selectType.value === '新建流程对象') {
        emit('success', currentRecord.value);
        handleCancel();
      } else if (selectType.value === '新增参考文档') {
        emit('successDoc', currentRecord.value);
        handleCancel();
      } else if (selectType.value === '零件工作区关联图档') {
        emit('successDoc', fromRecord.value, currentRecord.value); // fromRecord.value为当前记录，currentRecord.value为选中记录
        handleCancel();
      }
    } finally {
      setModalProps({ confirmLoading: false });
      handleCancel();
    }
  }

  // 取消
  const handleCancel = () => {
    closeModal();
  };

  // 选择目录
  const selectDir = (selectedKeys) => {
    searchInfo.value.CurrentDirId = selectedKeys[0];
    reload();
  };

  // 初始化弹窗
  const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
    // type 新建流程对象
    setModalProps({ confirmLoading: false });
    // 获取目录接口
    getDirectoryLevel(getDirParam.value).then((res) => {
      dataSource.value = res;
    });
    selectType.value = data.type;
    fromRecord.value = data.record ?? {};
  });

  // 表格初始化
  const [registerTable, { reload }] = useTable({
    columns: getDocumentColumns(),
    api: getPrdFileList,
    rowSelection: {
      type: 'radio',
      onSelect: (record) => {
        currentRecord.value = record;
      },
    },
    customRow: (record) => {
      return {
        onClick: () => {
          currentRecord.value = record;
        },
      };
    },
    bordered: true,
    formConfig: getDocumentConfig(), // 表单配置
    useSearchForm: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    canResize: true,
    scroll: { y: 300 },
  });
</script>

<style lang="less" scoped></style>
